package com.kingre.et.util;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.kingre.et.Constants;

public class MailUtil {
    private static final Logger logger = Logger.getLogger(MailUtil.class);
    
    //要发送Mail地址
    private String mailTo = "kingre79@sina.com";
    //Mail发送的起始地址
    private String mailFrom = "yjg5@163.com";
    //SMTP主机地址
    private String smtpHost = "smtp.163.com";
    //是否采用调试方式
    private boolean debug = false;

    private String messageBasePath = null;
    //Mail主题
    private String subject = "没指定标题";
    //Mail内容
    private String msgContent = "没指定内容";

    private Vector attachedFileList;
    private String mailAccount = null;
    private String mailPass = null;
    private String messageContentMimeType ="text/html; charset=gb2312";
 
    private String mailbccTo = null;
    private String mailccTo = null;

    private void fillMail(Session session,MimeMessage msg) throws IOException, MessagingException{

        String fileName = null;
        Multipart mPart = new MimeMultipart();
        if (mailFrom != null) {
            msg.setFrom(new InternetAddress(mailFrom));
            logger.debug("发送人Mail地址："+mailFrom);
        } else {
            logger.debug("没有指定发送人邮件地址！");
            return;
        }
        if (mailTo != null) {
            InternetAddress[] address = InternetAddress.parse(mailTo);
            msg.setRecipients(Message.RecipientType.TO, address);
            logger.debug("收件人Mail地址："+mailTo);
        } else {
            logger.debug("没有指定收件人邮件地址！");
            return;
        }

        if (mailccTo != null) {
            InternetAddress[] ccaddress = InternetAddress.parse(mailccTo);
            logger.debug("CCMail地址："+mailccTo);
            msg.setRecipients(Message.RecipientType.CC, ccaddress);
        }
        if (mailbccTo != null) {
            InternetAddress[] bccaddress = InternetAddress.parse(mailbccTo);
            logger.debug("BCCMail地址："+mailbccTo);
            msg.setRecipients(Message.RecipientType.BCC, bccaddress);
        }
        msg.setSubject(subject);
        InternetAddress[] replyAddress = { new InternetAddress(mailFrom)};
        msg.setReplyTo(replyAddress);
        // create and fill the first message part
        MimeBodyPart mBodyContent = new MimeBodyPart();
        if (msgContent != null)
            mBodyContent.setContent(msgContent, messageContentMimeType);
        else
            mBodyContent.setContent("", messageContentMimeType);
        mPart.addBodyPart(mBodyContent);
        // attach the file to the message
        if (attachedFileList != null) {
            for (Enumeration fileList = attachedFileList.elements(); fileList.hasMoreElements();) {
                fileName = (String) fileList.nextElement();
                MimeBodyPart mBodyPart = new MimeBodyPart();
   
                // attach the file to the message
                FileDataSource fds = new FileDataSource(messageBasePath + fileName);
                logger.debug("Mail发送的附件为："+messageBasePath + fileName);
                mBodyPart.setDataHandler(new DataHandler(fds));
                mBodyPart.setFileName(fileName);
                mPart.addBodyPart(mBodyPart);
            }
        }
        msg.setContent(mPart);
        msg.setSentDate(new Date());
    }
    /**
     * 此处插入方法说明。
     */
    public void init(){
    }
    /**
     * @param mailTo
     * @param msgContent
     * @param subject
     */
    public MailUtil(String mailTo, String subject, String msgContent) {
        this.mailTo = mailTo;
        this.msgContent = msgContent;
        this.subject = subject;
    }
    /**
     * 发送e_mail，返回类型为int
     * 当返回值为0时，说明邮件发送成功
     * 当返回值为3时，说明邮件发送失败
     */
    public int sendMail() throws IOException, MessagingException {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new MailAuthenticator());
        session.setDebug(debug);
        MimeMessage msg = new MimeMessage(session);
        Transport trans = null;
        try {
            fillMail(session,msg);
            // send the message
            trans = session.getTransport("smtp");
            try {
                trans.connect(smtpHost, Constants.HUAWEI_MAIL_USER, Constants.HUAWEI_MAIL_PASSWORD);//, HUAWEI_MAIL_PASSWORD);
            } catch (AuthenticationFailedException e) {
                e.printStackTrace();
                logger.debug("连接邮件服务器错误：");
                return 3;
            } catch (MessagingException e) {
                logger.debug("连接邮件服务器错误：");
                return 3;
            }

            trans.send(msg);
            trans.close();
        } catch (MessagingException mex) {
            logger.debug("发送邮件失败：");
            mex.printStackTrace();
            Exception ex = null;
            if ((ex = mex.getNextException()) != null) {
                logger.debug(ex.toString());
                ex.printStackTrace();
            }
            return 3;
        } finally {
            try {
                if (trans != null && trans.isConnected())
                    trans.close();
            } catch (Exception e) {
                logger.debug(e.toString());
            }
        }
        logger.debug("发送邮件成功！");
        return 0;
    }


    public static void main(String[] argv) throws Exception
    {
        MailUtil sm = new MailUtil("kingre79@sina.com", "主题", "内容");
        sm.sendMail();
    }

}
